<template>
  <div>
    <el-form ref="buildingForm" :model="buildingForm" :rules="rules" label-width="80px" size="medium">
      <el-form-item label="地址" prop="address">
        <el-input v-model="buildingForm.address"></el-input>
      </el-form-item>
      <el-form-item label="楼栋名称" prop="buildingName">
        <el-input v-model="buildingForm.buildingName"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="buildingForm.contactPhone"></el-input>
      </el-form-item>

      <el-form-item label="宿舍类型" prop="dormitoryType">
        <el-select v-model="buildingForm.dormitoryType">
          <el-option v-for="item in dormitoryTypeMap" :key="item" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="宿管" prop="housemasterId">
        <el-select v-model="buildingForm.housemasterId" multiple placeholder="请选择">
          <el-option v-for="item in housemaster" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>


      <el-form-item align="center">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button type="info" @click="resetForm">清除</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      housemaster: [],// 存储从后端获取的宿管数据
      buildingForm: {
        buildingId: '',
        address: '',
        buildingName: '',
        contactPhone: '',
        dormitoryType: '',
        housemasterId: ''
      },
      dormitoryTypeMap: [
        {
          value: 0,
          label: "女生宿舍"
        },
        {
          value: 1,
          label: "男生宿舍"
        },
        {
          value: 2,
          label: "混合宿舍"
        },
      ],
      rules: {
        address: [{required: true, message: '请输入地址', trigger: 'blur'}],
        buildingName: [{required: true, message: '请输入楼栋名称', trigger: 'blur'}],
        contactPhone: [
          {required: true, message: '请输入联系电话', trigger: 'blur'},
          {pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
        ],
        dormitoryType: [{required: true, message: '请选择宿舍类型', trigger: 'change'}],
        housemasterId: [{required: true, message: '请输入宿管', trigger: 'blur'}]
      }
    };
  },
  mounted() {
    // 在组件挂载后立即发送请求,查询宿舍列表
    this.fetchUsers();
  },
  methods: {
    submitForm() {
      this.$refs.buildingForm.validate(valid => {
        if (valid) {
          // 构建楼栋信息对象
          const requestBody = {
            address: this.buildingForm.address,
            buildingName: this.buildingForm.buildingName,
            contactPhone: this.buildingForm.contactPhone,
            dormitoryType: this.buildingForm.dormitoryType,
            housemasterId: this.buildingForm.housemasterId.join(',')
          };
          // 发送 POST 请求
          this.$axios.post('/api/buildings/add', requestBody, {headers: {'token': this.$store.getters.getToken}})
              .then(response => {
                this.resetForm();
                // 自定义一个事件，使其能够添加成功之后自动隐藏！
                this.$emit('buildingAdded');
                // 处理登录成功的情况，比如保存用户信息到本地存储或者跳转到其他页面
                if (response.data.code === 200) {
                  this.$message({
                    message: '添加成功',
                    type: 'success'
                  });
                } else {
                  this.$message.error(response.data.msg || '添加楼栋失败');
                }
              })
              .catch(error => {
                this.resetForm();
                // 自定义一个事件，使其能够添加成功之后自动隐藏！
                this.$emit('buildingAdded');
                // 处理错误情况
                this.$message({
                  message: '添加失败',
                  type: 'error'
                });
              });
        } else {
          return false;
        }
      });
    },
    // 重置表单
    resetForm() {
      this.$refs.buildingForm.resetFields();
    },
    // 查询用户(查询宿管)
    fetchUsers() {
      // 发送 POST 请求获取用户列表
      this.$axios.post('/api/users/list', {
        avatarUrl: "",
        clbum: "",
        contactInfo: "",
        createdAt: "",
        department: "",
        email: "",
        gender: "",
        isLocked: null,
        name: "",
        password: "",
        role: "0",
        token: "",
        userId: ""
      }, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        // 请求成功，从响应中提取出需要的数据
        const data = response.data;
        if (data.code === 200) {
          // 使用 reduce 构建以 userId 为键，name 为值的对象
          this.housemaster = data.data.reduce((arr, user) => {
            // 将当前用户的 userId 作为键，name 作为值，添加到累积的数组中
            arr.push({value: user.userId, label: user.name});
            return arr;
          }, []);
        } else {
          // 请求失败，显示错误信息
          this.$message.error(response.data.msg || '获取宿管列表失败');
        }
      })
          .catch(error => {
            // 请求错误，显示错误信息
            console.error('Error fetching users:', error);
            this.$message.error('获取用户列表失败');
          });
    }
  }
};
</script>

<style scoped>
/* 样式可以根据实际需要进行调整 */
</style>
